<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Download, Delete } from '@element-plus/icons-vue';
import { DeliveryService, type DeliveryData, type DeliveryQueryParams } from '@/services/deliveryService';

// 表格数据
const tableData = ref<DeliveryData[]>([]);
const loading = ref(false);

// 选中的行
const selectedRows = ref<DeliveryData[]>([]);

// 处理多选
const handleSelectionChange = (selection: DeliveryData[]) => {
  selectedRows.value = selection;
};

// 查看详情
const handleViewDetail = (row: DeliveryData) => {
  console.log('查看详情', row);
  // TODO: 这里应该跳转到配送详情页面
};

// 签收
const handleSign = async (row: DeliveryData) => {
  try {
    await ElMessageBox.confirm(
      `确定要签收运单 ${row.orderNo} 吗？`,
      '签收确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const result = await DeliveryService.signDelivery(row.objectId!);
    
    if (result.success) {
      ElMessage.success('签收成功');
      loadData();
    } else {
      ElMessage.error('签收失败');
    }
  } catch (error) {
    // 用户取消操作或其他错误
  }
};

// 拒签
const handleReject = async (row: DeliveryData) => {
  try {
    const { value: reason } = await ElMessageBox.prompt(
      '请输入拒签原因',
      '拒签确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入拒签原因'
      }
    );

    const result = await DeliveryService.rejectDelivery(row.objectId!, {
      rejectReason: reason
    });
    
    if (result.success) {
      ElMessage.success('拒签成功');
      loadData();
    } else {
      ElMessage.error('拒签失败');
    }
  } catch (error) {
    // 用户取消操作或其他错误
  }
};

// 搜索关键词
const searchWaybillNo = ref('');
const searchSenderInfo = ref('');
const searchReceiverInfo = ref('');

// 状态选择
const deliveryStatus = ref('');
const deliveryStatusOptions = [
  { label: '全部', value: '' },
  { label: '待签收', value: 0 },
  { label: '已签收', value: 1 },
  { label: '已拒签', value: 2 }
];

// 付款方式
const paymentMethod = ref('');
const paymentMethodOptions = [
  { label: '全部', value: '' },
  { label: '预付', value: 1 },
  { label: '到付', value: 2 },
  { label: '月结', value: 3 }
];

// 加载数据方法
const loadData = async () => {
  loading.value = true;
  try {
    const params: DeliveryQueryParams = {
      cargoNo: searchWaybillNo.value,
      senderInfo: searchSenderInfo.value,
      receiverInfo: searchReceiverInfo.value,
      status: deliveryStatus.value ? Number(deliveryStatus.value) : undefined,
      paymentMethod: paymentMethod.value ? Number(paymentMethod.value) : undefined,
      page: currentPage.value,
      pageSize: pageSize.value
    };

    const result = await DeliveryService.getDeliveryList(params);
    
    if (result.success) {
      tableData.value = result.data;
      total.value = result.total;
    } else {
      ElMessage.error('获取数据失败');
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (date: Date | string): string => {
  if (!date) return '';
  const d = new Date(date);
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 执行搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

// 重置搜索条件
const handleReset = () => {
  searchWaybillNo.value = '';
  searchSenderInfo.value = '';
  searchReceiverInfo.value = '';
  deliveryStatus.value = '';
  paymentMethod.value = '';
  currentPage.value = 1;
  loadData();
};

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(50);

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadData();
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadData();
};

// 导出
const handleExport = () => {
  ElMessage.success('配送数据导出成功');
};

// 组件初始化时加载数据
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="delivery-list-container">
    <div class="search-form">
      <div class="search-form-row">
        <el-input v-model="searchWaybillNo" placeholder="请输入货号搜索" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-input v-model="searchSenderInfo" placeholder="请输入发货人信息搜索" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-input v-model="searchReceiverInfo" placeholder="请输入收货人信息搜索" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select v-model="deliveryStatus" placeholder="配送状态" clearable>
          <el-option
            v-for="item in deliveryStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-select v-model="paymentMethod" placeholder="付款方式" clearable>
          <el-option
            v-for="item in paymentMethodOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        
        <div class="button-group">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>
    </div>
    
    <div class="action-bar">
      <div class="left-actions">
        <el-button @click="handleExport">导出</el-button>
        <el-button :icon="Refresh" @click="loadData">刷新</el-button>
      </div>
      <div class="right-actions">
        <el-alert
          title="可左右滑动查看更多字段"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
    </div>
    
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column label="货号" prop="cargoNo" width="120" fixed="left" />
        <el-table-column label="运单号" prop="orderNo" width="120" fixed="left" />
        <el-table-column label="收货人" prop="receiverName" width="100" />
        <el-table-column label="收货人电话" prop="receiverPhone" width="120" />
        <el-table-column label="收货人地址" prop="receiverAddress" min-width="200" show-overflow-tooltip />
        <el-table-column label="发货人" prop="senderName" width="100" />
        <el-table-column label="发货人电话" prop="senderPhone" width="120" />
        <el-table-column label="发货人地址" prop="senderAddress" min-width="200" show-overflow-tooltip />
        <el-table-column label="货物类型" prop="cargoType" width="100" />
        <el-table-column label="总数量" prop="totalQuantity" width="100" />
        <el-table-column label="总体积(方)" prop="totalVolume" width="120" />
        <el-table-column label="总重量(KG)" prop="totalWeight" width="120" />
        <el-table-column label="付款方式" width="100">
          <template #default="{ row }">
            {{ DeliveryService.getPaymentMethodText(row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column label="声明价值" prop="declaredValue" width="100" />
        <el-table-column label="保费" prop="insuranceFee" width="100" />
        <el-table-column label="配送费" prop="deliveryFee" width="100" />
        <el-table-column label="卸货费" prop="unloadingFee" width="100" />
        <el-table-column label="代收货款" prop="collectOnDelivery" width="100" />
        <el-table-column label="配送时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.deliveryTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" fixed="right">
          <template #default="{ row }">
            <el-tag 
              :type="row.status === 0 ? 'warning' : (row.status === 1 ? 'success' : 'danger')"
            >
              {{ DeliveryService.getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">详情</el-button>
            <el-button 
              v-if="row.status === 0" 
              type="success" 
              link 
              @click="handleSign(row)"
            >
              签收
            </el-button>
            <el-button 
              v-if="row.status === 0" 
              type="danger" 
              link 
              @click="handleReject(row)"
            >
              拒签
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="pagination-container">
      <div class="pagination-info">
        共 {{ total }} 条
      </div>
      <div class="pagination-size">
        <el-select v-model="pageSize" @change="handleSizeChange">
          <el-option :value="10" label="10条/页" />
          <el-option :value="20" label="20条/页" />
          <el-option :value="50" label="50条/页" />
          <el-option :value="100" label="100条/页" />
        </el-select>
      </div>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
      />
      <div class="pagination-jump">
        前往 <el-input v-model="currentPage" type="number" size="small" style="width: 50px" /> 页
      </div>
    </div>
  </div>
</template>

<style scoped>
.delivery-list-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  width: 100%;
}

.search-form-row {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  width: 100%;
}

.search-form-row:last-child {
  margin-bottom: 0;
}

.search-form-row > * {
  flex: 1;
  min-width: 0;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  min-width: 180px;
  flex: 0 0 auto;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  align-items: center;
}

.left-actions {
  display: flex;
  gap: 10px;
}

.right-actions {
  display: flex;
  align-items: center;
}

.right-actions .el-alert {
  padding: 8px 12px;
  margin: 0;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.pagination-jump {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
}

.el-table {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
  width: 100%;
}
</style>